<template>
  <div class="app-container org">
    <!-- 左侧区域 -->
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->
      <div>
        <p class="pinformation">搜索条件</p>
        <el-form :model="queryParams" ref="queryRef" label-width="70">
          <el-row>
            <el-col :span="16">
              <el-form-item label="客户名称：" prop="customName">
                <el-input v-model="queryParams.customName" placeholder="请输入客户名称" maxlength="100" clearable
                  @keyup.enter="handleQuery" />
              </el-form-item></el-col>
            <el-col :span="8">
              <el-row justify="end">
                <el-button type="success" @click="handleQuery">搜索</el-button>
                <el-button class="resetBtn" @click="resetQuery">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
          <el-form-item label="所在区域：">
            <City @queryParam="cityQueryParam" :id="'left'" ref="areaRef" />
          </el-form-item>
        </el-form>
      </div>
      <!-- /搜索条件盒子 -->

      <!-- 客户列表表格区域 -->
      <div style="margin-top: 10px">
        <el-row style="justify-content: space-between">
          <el-row>
            <p class="pinformation">客户列表</p>
            <p class="totalStyle">共{{ total }}条数据</p>
          </el-row>
          <el-row style="padding-bottom: 5px">
            <el-button type="success" link icon="Plus" @click="handleAdd">新增</el-button>
            <!-- <el-button type="success" link icon="Delete" @click="handleDelete"
              :disabled="multiple > 0 ? false : true">删除</el-button> -->
          </el-row>
        </el-row>

        <el-table ref="mainTableRef" class="business" v-loading="loading" :highlight-current-row="highLightRow"
          :data="clientList" @row-click="rowClick">
          <el-table-column label="客户名称" align="center" prop="customName" />

          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="success" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
      <!-- /客户列表表格区域 -->
    </el-card>
    <!-- /左侧区域 -->

    <!-- 右侧区域 -->
    <div class="rightCard">
      <el-card style="margin-bottom: 0.75vh">
        <!-- 基础信息区域 -->
        <el-form label-width="120px" :model="form" ref="customRef" :rules="rules">
          <div>
            <el-row style="margin-bottom: 5px">
              <el-col :span="22">
                <p class="pinformation">基础信息</p>
              </el-col>
              <el-col :span="2">
                <el-button type="success" size="small" @click="submitForm(false)">保存</el-button>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="客户名称：" prop="customName">
                  <el-input v-model="form.customName" placeholder="请输入客户名称" clearable maxlength="100" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户属性：" prop="customPropertys">
                  <el-select style="width: 100%" clearable v-model="form.customPropertys" multiple placeholder="请选择客户属性">
                    <el-option v-for="dict in sys_custom_property" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-row>
                  <el-col>
                    <el-form-item label="所在区域：" prop="areaCode">
                      <City @queryParam="cityQueryParam" :id="'right'" @areaCode="areaCode" :viewForm="viewCity" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="12">
                <el-form-item label="详细地址：" prop="address">
                  <el-input v-model="form.address" placeholder="请输入详细地址" clearable maxlength="100" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="联系人：" prop="contactsName">
                  <el-input v-model="form.contactsName" placeholder="联系人" clearable maxlength="8" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="联系电话：" prop="contactsPhonenumber">
                  <el-input v-model="form.contactsPhonenumber" placeholder="联系电话" clearable maxlength="15" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="传真：" prop="fax">
                  <el-input v-model="form.fax" placeholder="请输入传真" clearable maxlength="20" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="邮箱：" prop="email">
                  <el-input v-model="form.email" placeholder="请输入邮箱" clearable maxlength="50" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="票据类型：" prop="invoiceType">
                  <el-select v-model="form.invoiceType" placeholder="请选择发票类型" clearable>
                    <el-option v-for="dict in sys_invoice_type" :key="parseInt(dict.value)" :label="dict.label"
                      :value="parseInt(dict.value)" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="发票税率(%)：" prop="invoiceCount">
                  <el-input type="number" v-model="form.invoiceCount" placeholder="请输入发票税率" clearable maxlength="100" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="东经（度）：" prop="jd">
                  <el-input v-model="form.jd" placeholder="输入东经（度）" clearable maxlength="15">
                    <template #suffix>
                      <el-icon class="el-input__icon" @click="editJdClick('custom')">
                        <Edit />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="北纬（度）：" prop="wd">
                  <el-input v-model="form.wd" placeholder="输入北纬（度）" clearable maxlength="15">
                    <template #suffix>
                      <el-icon class="el-input__icon" @click="editWdClick('custom')">
                        <Edit />
                      </el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="银行账号：" prop="bankName">
                  <el-input v-model="form.bankName" placeholder="请输入银行账号" clearable maxlength="50" />
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item label="开户行：" prop="bankNumber">
                  <el-input placeholder="请输入开户行" v-model="form.bankNumber" clearable maxlength="50" />
                </el-form-item>
              </el-col>
              <el-col :span="9">
                <el-form-item label="纳税人识别号：" prop="taxpayerNumber">
                  <el-input v-model="form.taxpayerNumber" placeholder="请输入纳税人识别号" clearable maxlength="100" />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <!-- /基础信息区域 -->
      </el-card>

      <!-- 右下区域 -->
      <el-card>
        <el-tabs v-model="activeName" @tab-change="tabchange">
          <el-tab-pane label="污染源信息" name="first">
            <el-row style="justify-content: space-between">
              <el-row>
                <p class="pinformation">点位列表</p>
                <p class="totalStyle">共 {{ pointList?.length }}条数据</p>
              </el-row>
              <el-row style="padding-bottom: 5px">
                <el-button type="success" link icon="Plus" @click="ptBtnClick" :disabled="!customId">新增</el-button>
              </el-row>
              <el-col :span="14">
                <p class="pinformation">基础信息</p>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="10">
                <el-table class="business" ref="sub1TableRef" v-loading="pointTableLoading"
                  :highlight-current-row="highLightRow" :data="pointList" @row-click="ponitRowClick">
                  <el-table-column label="点位名称" align="center" prop="pointName" width="250" show-overflow-tooltip />
                  <el-table-column label="检测类别" align="center" prop="jclbId" show-overflow-tooltip>
                    <template #default="scope">
                      {{ getJclbName(scope.row) }}
                    </template>
                  </el-table-column>

                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
                    <template #default="scope">
                      <el-button link type="success" icon="Edit" @click="editClick(scope.row)">编辑</el-button>
                      <el-button link type="success" icon="Delete" @click="pointDeleteBtnClick(scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table></el-col>
              <el-col :span="14">
                <el-form label-width="90px" :model="pointForm">
                  <el-row>
                    <el-col :span="14">
                      <el-form-item label="点位名称：">
                        {{ pointForm.pointName || "/" }}
                      </el-form-item>
                    </el-col>
                    <el-col :span="10">
                      <el-form-item label="检测类别：" prop="jcxmName">
                        {{
                          proxy.getItemByArray(
                            jclbTypeList,
                            "jclbId",
                            pointForm.jclbId,
                            "jclbName"
                          ) || "/"
                        }}
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="7">
                      <el-form-item label="东经（度）：">
                        {{ pointForm.jd || "/" }}
                      </el-form-item>
                    </el-col>
                    <el-col :span="7">
                      <el-form-item label="北纬（度）：">
                        {{ pointForm.wd || "/" }}
                      </el-form-item>
                    </el-col>
                    <el-col :span="10">
                      <el-form-item label="采样方式：">
                        {{
                          proxy.getItemByArray(
                            sys_sample_type,
                            "value",
                            pointForm.sampleType,
                            "label"
                          ) || "/"
                        }}
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="连测天数：" label-width="90px">
                        {{ pointForm.sampleDay || "/" }}
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="每天频次：">
                        {{ pointForm.sampleCount || "/" }}
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="检测周期：" prop="jcxmName" label-width="85px">
                        {{
                          proxy.getItemByArray(
                            sys_point_cycle,
                            "value",
                            pointForm.cycleType,
                            "label"
                          ) || "/"
                        }}
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="排序号：" label-width="70px">
                        {{ pointForm.orderId || "/" }}
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
                <el-row>
                  <p class="pinformation">检测项目列表</p>
                  <p class="totalStyle">共 {{ taskJcxmTotal }} 条数据</p>
                  <el-table ref="subTableRef" class="business" v-loading="projectTableLoading"
                    :highlight-current-row="highLightRow" :data="taskJcxmList">
                    <el-table-column label="检测项目" align="center" prop="methodJcxm.jcxmName" show-overflow-tooltip>
                      <template #default="scope">
                        <span v-html="transformation(scope.row.methodJcxm.jcxmName)"></span>
                      </template>
                    </el-table-column>
                    <el-table-column label="方法编号" align="center" prop="methodJcxm.methodCode" show-overflow-tooltip />
                    <el-table-column label="方法名称" align="center" prop="methodJcxm.methodName" width="200"
                      show-overflow-tooltip />
                    <el-table-column label="特别选项" align="center" />
                    <el-table-column label="天数" align="center" prop="sampleDay" width="60" />
                    <el-table-column label="频次" align="center" prop="sampleCount" width="60" />
                  </el-table>
                  <pagination v-show="total > 0" :total="taskJcxmTotal" v-model:page="queryTaskJcxmForm.pageNum"
                    v-model:limit="queryTaskJcxmForm.pageSize" @pagination="getTaskJcxmList" />
                </el-row>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="在线设备" name="second">
            <el-row>
              <el-row style="justify-content: space-between">
                <el-row>
                  <p class="pinformation">在线设备列表</p>
                  <p class="totalStyle">
                    共 {{ deviceList?.length || 0 }} 条数据
                  </p>
                </el-row>
                <el-row style="padding-bottom: 5px">
                  <el-button type="success" link icon="Plus" @click="deviceBasicInfoAddBtnClick" :disabled="!customId">新增</el-button>
                </el-row>
              </el-row>
              <el-row :gutter="10">
                <el-col :span="10">
                  <el-table class="business" ref="sub2TableRef" v-loading="loading" :highlight-current-row="highLightRow"
                    :data="deviceList" @row-click="deviceListRowClick">
                    <el-table-column label="安装位置" align="center" prop="location" />
                    <el-table-column label="检测类别" align="center" prop="jclbId">
                      <template #default="scope">
                        {{ getJclbName(scope.row) }}
                      </template>
                    </el-table-column>

                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                      <template #default="scope">
                        <el-button link type="success" icon="Delete"
                          @click="deleteDeviceListItemBtnClick(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table></el-col>
                <el-col :span="14">
                  <el-row style="margin-bottom: 10px">
                    <el-col :span="22">
                      <p class="pinformation">基础信息</p>
                    </el-col>
                    <el-col :span="2">
                      <el-button type="success" size="small" @click="addDeviceInfoSaveBtnClick(false)" :disabled="!customId">保存</el-button>
                    </el-col>
                  </el-row>
                  <el-form :model="addDeviceInfo" :rules="deviceInfoRules" ref="addDeviceInfoRef" label-width="100px">
                    <el-row>
                      <el-col :span="14">
                        <el-form-item label="安装位置：" prop="location">
                          <el-input v-model="addDeviceInfo.location" placeholder="请输入安装位置" clearable maxlength="100" />
                        </el-form-item>
                      </el-col>
                      <el-col :span="10">
                        <el-form-item label="检测类别：" prop="jclbId">
                          <el-select clearable v-model="addDeviceInfo.jclbId" placeholder="请选择检测类别">
                            <el-option v-for="item in jclbTypeList" :key="item.jclbId" :label="item.jclbName"
                              :value="item.jclbId" />
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row>
                      <el-col :span="7">
                        <el-form-item label="东经（度）：" prop="jd">
                          <el-input v-model="addDeviceInfo.jd" placeholder="请输入东经（度）" clearable maxlength="100">
                            <template #suffix>
                              <el-icon class="el-input__icon" @click="editJdClick('addDeviceInfo')">
                                <Edit />
                              </el-icon>
                            </template>
                          </el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="7">
                        <el-form-item label="北纬（度）：" prop="wd">
                          <el-input v-model="addDeviceInfo.wd" placeholder="请输入北纬（度）" clearable maxlength="100">
                            <template #suffix>
                              <el-icon class="el-input__icon" @click="editWdClick('addDeviceInfo')">
                                <Edit />
                              </el-icon>
                            </template>
                          </el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="9">
                        <el-form-item label="排序号：" label-width="100px" prop="orderId">
                          <el-input v-model="addDeviceInfo.orderId" clearable placeholder="请输入排序号" maxlength="100" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row> </el-row>
                  </el-form>
                  <el-row style="justify-content: space-between">
                    <el-row>
                      <p class="pinformation">检测项目列表</p>
                      <p class="totalStyle">
                        共
                        {{ addDeviceInfo.deviceJcxmList?.length || 0 }} 条数据
                      </p>
                    </el-row>
                    <el-row style="padding-bottom: 5px">
                      <el-button type="success" link icon="Plus" @click="addBtnClick">新增</el-button>
                    </el-row>
                    <el-table ref="sub3TableRef" class="business" v-loading="loading"
                      :highlight-current-row="highLightRow" :data="addDeviceInfo.deviceJcxmList">
                      <el-table-column label="设备名称" align="center" prop="deviceName" />
                      <el-table-column label="检测项目" align="center" prop="jcxmName">
                        <template #default="scope">
                          <span v-html="transformation(scope.row.jcxmName)"></span>
                        </template>
                      </el-table-column>
                      <el-table-column label="生产厂商" align="center" prop="deviceVender" />
                      <el-table-column label="参比方法号" align="center" prop="methodCode" />
                      <el-table-column label="参比方法" align="center" prop="methodName" />
                      <el-table-column label="操作" align="center" prop="jclbName" width="145">
                        <template #default="scope">
                          <el-button link type="success" icon="edit" @click="editDeviceInfo(scope.row)">编辑</el-button>
                          <el-button link type="success" icon="Delete" @click="deleteMethodItem(scope.row)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-row>
                </el-col>
              </el-row>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!-- /右下区域 -->
    </div>
    <!-- /右侧区域 -->
    <el-dialog :class="'el-dialog-theme3'" v-model="jdDialog" title="修改经度" width="20%" draggable
      :close-on-click-modal="false">
      <el-form-item label="经度：">
        <el-row>
          <el-col :span="6">
            <el-input placeholder="度" maxlength="100" clearable v-model="jwdForm.degrees" />
          </el-col>
          <el-col :span="2" style="text-align: center"> 度 </el-col>
          <el-col :span="6">
            <el-input v-model="jwdForm.minutes" placeholder="分" maxlength="100" clearable />
          </el-col>
          <el-col :span="2" style="text-align: center"> 分 </el-col>
          <el-col :span="6">
            <el-input v-model="jwdForm.seconds" placeholder="秒" maxlength="100" clearable />
          </el-col>
          <el-col :span="2" style="text-align: center"> 秒 </el-col>
        </el-row>
      </el-form-item>
      <template #footer>
        <el-button type="success" @click="jdSave"> 保存 </el-button>
        <el-button @click="jdDialog = false" type="danger">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" v-model="wdDialog" title="修改纬度" width="20%" draggable
      :close-on-click-modal="false">
      <el-form-item label="纬度：" prop="deviceName">
        <el-row>
          <el-col :span="6">
            <el-input placeholder="度" maxlength="100" clearable v-model="jwdForm.degrees" />
          </el-col>
          <el-col :span="2" style="text-align: center"> 度 </el-col>
          <el-col :span="6">
            <el-input v-model="jwdForm.minutes" placeholder="分" maxlength="100" clearable />
          </el-col>
          <el-col :span="2" style="text-align: center"> 分 </el-col>
          <el-col :span="6">
            <el-input v-model="jwdForm.seconds" placeholder="秒" maxlength="100" clearable />
          </el-col>
          <el-col :span="2" style="text-align: center"> 秒 </el-col>
        </el-row>
      </el-form-item>
      <template #footer>
        <el-button type="success" @click="wdSave"> 保存 </el-button>
        <el-button @click="wdDialog = false" type="danger">取消</el-button>
      </template>
    </el-dialog>
    <el-dialog :class="'el-dialog-theme3'" v-model="isShowAddDialog" title="新增/编辑检查项目" width="40%"
      @close="closedDialog" draggable :close-on-click-modal="false">
      <el-form :model="deviceForm" :rules="dialogRules" ref="dialogRef" label-width="100px">
        <el-form-item label="设备名称：" prop="deviceName">
          <el-input v-model="deviceForm.deviceName" placeholder="请输入设备名称" maxlength="100" clearable />
        </el-form-item>
        <el-form-item label="仪器型号：" prop="deviceCode">
          <el-input v-model="deviceForm.deviceCode" clearable placeholder="请输入仪器型号" maxlength="100" />
        </el-form-item>
        <el-form-item label="生产厂商：" prop="deviceVender">
          <el-input v-model="deviceForm.deviceVender" placeholder="请输入生产厂商" clearable maxlength="100" />
        </el-form-item>
        <el-form-item label="出厂编号：" prop="venderCode">
          <el-input v-model="deviceForm.venderCode" placeholder="请输入出厂编号" clearable maxlength="100" />
        </el-form-item>
        <el-form-item label="检测方法：" prop="method">
          <el-input v-model="deviceForm.method" placeholder="请输入检测方法" clearable maxlength="100" />
        </el-form-item>
        <el-form-item label="检测项目：" prop="jcxmId">
          <el-select clearable filterable v-model="deviceForm.jcxmId" placeholder="请选择检测项目" style="width: 100%"
            @change="jcxmSelectChange">
            <el-option v-for="item in jcxmList" :key="item.jcxmId" :label="item.jcxmName" :value="item.jcxmId">
              <span v-html="proxy.getSupAndSub(item.jcxmName)"></span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参比方法：" prop="mJId">
          <el-select clearable v-model="deviceForm.mJId" placeholder="请选择参比方法" style="width: 100%" filterable>
            <el-option v-for="item in methodList" :key="item.mJId" :label="item.methodCode + item.methodName"
              :value="item.mJId" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-row style="justify-content: space-between">
        <el-row>
          <p class="pinformation">技术指标</p>
          <p class="totalStyle">
            共 {{ deviceForm.deviceJcxmTargetList?.length }} 条数据
          </p>
        </el-row>
        <el-row style="padding-bottom: 5px">
          <el-button type="success" link icon="Plus" @click="addNewRowBtnClick">新增</el-button>
        </el-row>
        <el-table class="business targetTable" v-loading="loading" :highlight-current-row="highLightRow"
          :data="deviceForm.deviceJcxmTargetList" height="200">
          <el-table-column label="序号" width="60" align="center" type="index" />
          <el-table-column label="技术指标要求" align="center" prop="techName">
            <template #default="scope">
              <el-input v-model="scope.row.techName" maxlength="100" clearable />
            </template>
          </el-table-column>
          <el-table-column label="实验指标要求" align="center" prop="labName">
            <template #default="scope">
              <el-input v-model="scope.row.labName" maxlength="100" clearable />
            </template>
          </el-table-column>
          <el-table-column label="样品数量要求" align="center" prop="sampleName">
            <template #default="scope">
              <el-input v-model="scope.row.sampleName" maxlength="100" clearable />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="145">
            <template #default="scope">
              <el-button link type="success" icon="Delete" @click="deleteDialogNewRows(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <template #footer>
        <el-button type="success" @click="addOrEditSaveBtnClick">
          保存
        </el-button>
        <el-button @click="addOrEditCancelBtnClick" type="danger">取消</el-button>
      </template>
    </el-dialog>

    <PointLocationDialog ref="PTDialogRef" :pointId="pointId" @destroyPointDialog="destroyPointDialog"
      :primaryKeyId="customId" v-if="pointDialogDestroy" :queryPointList="queryPointList" />
  </div>
</template>

<script setup name="custom">
import { allListJclb } from "@/api/store/jclb";
import { getLatiAndLong, getDms } from "@/api/common";
import {
  pageListCustom,
  addCustom,
  getCustom,
  delCustom,
} from "@/api/contract/custom";
import {
  listPoint1,
  listTaskJcxm,
  getPoint,
  delPoint,
} from "@/api/contract/taskPoint";
import {
  listDevice,
  addBasicDeviceInfoAPI,
  getDevice,
  addOrEditMethodAPI,
  getJcxmList,
  getArgumentsMethodIdAPI,
  delDevice,
  echoAPI,
  deleteJcxmAPI,
} from "@/api/contract/device";
import { getSeqId } from "@/api/common";

import City from "@/components/City/index.vue";
import useOrg from "@/store/modules/org";
import { onMounted, ref } from "vue";
import PointLocationDialog from "../point/index.vue";

const { proxy } = getCurrentInstance();
const orgStore = useOrg(); // 城市相关
const loading = ref(false); // 客户列表加载
const ids = ref([]);
const jdDialog = ref(false);
const wdDialog = ref(false);
const multiple = ref(false);
const total = ref(0); // 总条数
const taskJcxmTotal = ref(0); // 检测项目总条数
const highLightRow = ref(true); // 表格 => 点击选中激活样式
const activeName = ref("first"); // 选项卡默认值
const jclbTypeList = ref([]); // 检测类别 list
const isShowAddDialog = ref(false); // 控制新增Dialog的显示/隐藏
const clientList = ref([]); // 客户信息列表 list
const areaRef = ref(null); // 获取城市组件
const deviceList = ref([]); // 在线设备列表 list
const jcxmList = ref([]); // 检测项目 select
const methodList = ref([]); // 参比方法号 select
const customId = ref(""); // 客户id
const pointTableLoading = ref(false); // 点位表格加载
const projectTableLoading = ref(false); // 检测方法加载
const PTDialogRef = ref(null); // 新增/编辑检测方法dialog
const pointId = ref();
const pointDialogDestroy = ref(false);
// dialog表单校验
const dialogRules = ref({
  deviceName: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
});

// 在线设备弹出层 form
const deviceForm = ref({
  deviceJcxmTargetList: [],
});
const {
  sys_custom_property,
  sys_invoice_type,
  sys_sample_type,
  sys_point_cycle,
} = proxy.useDict(
  "sys_custom_property",
  "sys_sample_type",
  "sys_invoice_type",
  "sys_point_cycle"
);

const pointList = ref([]); // 点位列表

// 点位列表基础信息区域
const pointForm = ref({});
const taskJcxmList = ref([]);
// 新增设备基础信息区域
const addDeviceInfo = ref({
  deviceJcxmList: [],
  orderId: 0,
});

const data = reactive({
  form: {
    customName: "", // 客户名称
    invoiceType: 1, // 默认选中专用发票
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cityCode: -1,
    areaCode: -1,
    provinceCode: -1,
  },
  rules: {
    customName: [
      { required: true, message: "客户名称不能为空", trigger: "blur" },
    ],
    jd: [
      {
        pattern:
          /^(((\d|[1-9]\d|1[1-7]\d|0)\.\d{0,6})|(\d|[1-9]\d|1[1-7]\d|0{1,3})|180\.0{0,6}|180)$/,
        message: "输入错误",
        trigger: "blur",
      },
    ],
    wd: [
      {
        pattern: /^([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/,
        message: "输入错误",
        trigger: "blur",
      },
    ],
    email: [
      {
        pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
        message: "邮箱格式不符合规范",
        trigger: "blur",
      },
    ],
    bankName: [
      {
        pattern: /^([0-9 ])*$/,
        message: "请输入数字或者空格",
        trigger: "blur",
      },
    ],
    fax: [
      {
        pattern: /^([0-9\- ])*$/,
        message: "请输入传真格式",
        trigger: "blur",
      },
    ],
    taxpayerNumber: [
      {
        pattern: /^([0-9a-zA-Z])*$/,
        message: "请输入数字或者字母",
        trigger: "blur",
      },
    ],
    contactsPhonenumber: [
      {
        pattern: /^\d{11}$/,
        message: "请输入正确的手机号码",
        trigger: "blur",
      },
    ],
  },
  queryTaskJcxmForm: {
    pageNum: 1,
    pageSize: 10,
  },
});

const { queryParams, form, rules, queryTaskJcxmForm } = toRefs(data);

onMounted(() => {
  getJclbTypeList();
  getList();
  nextTick(function () {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
})

onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

function destroyPointDialog() {
  pointDialogDestroy.value = false;
  pointId.value = null;
}
// 获取检测类别数据
function getJclbTypeList() {
  allListJclb({ typeId: 1 }).then((res) => {
    jclbTypeList.value = res.data;
  });
}

const getList = async () => {
  loading.value = true;
  const res = await pageListCustom(queryParams.value);
  clientList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

// 表单重置
function reset() {
  form.value = { customPropertys: [] };
  proxy.resetForm("customRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  areaRef.value.resetArea();
  nextTick(() => {
    handleQuery();
  });
}

const viewCity = ref({});
/** 客户列表点击切换 */
async function rowClick(row) {
  reset();
  taskJcxmList.value = []; // 重置点位列表右侧的检测项目列表
  addDeviceInfo.value.deviceJcxmList = []; // 重置设备信息列表右侧的检测项目列表
  highLightRow.value = true; // 点击开启高亮

  const res = await getCustom(row.customId); // 获取用户详情
  form.value = res.data;

  customId.value = row.customId; // 将客户id保存到customId
  await queryPointList(customId.value); // 获取点位列表

  const res2 = await listDevice({ customId: row.customId }); // 获取在线设备列表
  deviceList.value = res2.data;

  form.value.customPropertys = form.value.customProperty
    ? form.value.customProperty.split(",")
    : [];

  // 处理城市相关
  viewCity.value = {
    areaCode: res.data.areaCode,
    provinceCode: res.data.provinceCode,
    cityCode: res.data.cityCode,
  };
}

/** 提交按钮 */
const submitForm = (isAuto) => {
  return new Promise((resolve) => {
    proxy.$refs["customRef"].validate(async (valid) => {
      if (!valid) return Promise.reject(false);
      if (form.value.customPropertys.length) {
        form.value.customProperty = form.value.customPropertys.join(",");
      }

      const res = await addCustom(form.value); // 新增客户
      if (form.value.customId) {
        if (!isAuto) {
          proxy.$modal.msgSuccess("编辑成功");
        }
      } else {
        form.value.customId = res.data;
        if (!isAuto) {
          proxy.$modal.msgSuccess("新增成功");
        }
      }
      loading.value = false; // 关闭加载

      getList(); // 重新获取客户列表实现刷新
      resolve();
    });
  });
};

/** 删除按钮操作 */
function handleDelete(selection, row) {
  const _customIds = selection.customId || ids.value;
  proxy.$modal
    .confirm("删除该项目方法包将删除其所有详细信息数据，确定删除吗？")
    .then(function () {
      return delCustom(_customIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
      handleAdd();
    })
    .catch(() => { });
}

// 点击新增按钮 => 重置表单和表单错误提示信息与取消行默认选中样式
function handleAdd() {
  form.value = { customPropertys: [] };
  pointList.value = [];
  deviceList.value = [];
  viewCity.value = {};
  highLightRow.value = false;
  proxy.$refs["customRef"].clearValidate();
}

// 选项卡切换
function tabchange() {
  window.removeEventListener("resize", getTableHeight);
  nextTick(function () {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  });
}

// 自适应高度
const heightParams = ref([
  { tableName: "main", bottomHeight: 73 },
  { tableName: "sub", bottomHeight: 73 },
  { tableName: "sub1", bottomHeight: 21 },
  { tableName: "sub2", bottomHeight: 21 },
  { tableName: "sub3", bottomHeight: 21 },
]);

// 自适应高度
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}

// 在线设备 => 点击新增
const addBtnClick = () => {
  submitForm(true).then(() => {
    addDeviceInfoSaveBtnClick(true) // 添加设备基本信息保存按钮
      .then(async () => {
        const res2 = await getJcxmList(addDeviceInfo.value.jclbId); // 根据检测类别ID获取检测项目列表
        deviceForm.value.deviceId = addDeviceInfo.value.deviceId; // 将新增设备基础信息表单内的设备ID保存到新增dialog表单
        jcxmList.value = res2.data; // 保存检测方法列表
        isShowAddDialog.value = true; // 打开dialog
      })
      .catch(() => { });
  });
};

// 污染源信息 => 点位列表 => 点击表格编辑
const editClick = (row) => {
  pointDialogDestroy.value = true;
  nextTick(() => {
    PTDialogRef.value.isShowPTDialog = true; // 开启新增/编辑dialog
    //Object.assign({}, PTDialogRef.value.form, row) // 将两个对象合并
    pointId.value = row.pointId;
  });
};

// 点位列表点击新增跳转
const ptBtnClick = () => {
  // 表单校验
  submitForm(true).then(() => {
    pointDialogDestroy.value = true;
    nextTick(() => {
      PTDialogRef.value.form.primaryId = form.value.customId;
      // 打开新增/编辑检测方法dialog
      //pointId.value = "";
      PTDialogRef.value.isShowPTDialog = true;
    });
  });
  // PTDialogRef.value.resetForm(); // 重置dialog表单 // 多余
};

// 查询城市
const cityQueryParam = (val) => {
  if (val.id == "left") {
    queryParams.value = Object.assign(queryParams.value, val);
  } else if (val.id == "right") {
    form.value = Object.assign(form.value, val);
  }
};

function areaCode(val) {
  form.value.areaCode = val;
}

// 获取点位列表数据
const queryPointList = async (primaryId) => {
  pointTableLoading.value = true; // 开启加载
  const { data: res } = await listPoint1({ primaryId: primaryId }); // 根据客户id查询点位列表
  pointList.value = res; // 保存点位列表
  pointTableLoading.value = false; // 关闭加载
};

// 比对检测类别
function getJclbName(row) {
  return proxy.getItemByArray(
    jclbTypeList.value,
    "jclbId",
    row.jclbId,
    "jclbName"
  );
}

// 点击点位列表
const ponitRowClick = (row) => {
  loadPoint(row.pointId);
  loadTaskJcxm(row.pointId);
};
// 根据点位id获取点位详情
function loadPoint(pointId) {
  getPoint(pointId).then((res) => {
    pointForm.value = res.data; //回显点位详情
  });
}

function loadTaskJcxm(pointId) {
  queryTaskJcxmForm.value.pointId = pointId;
  queryTaskJcxmForm.value.pageNum = 1;
  getTaskJcxmList();
}
//查询检测项目列表
function getTaskJcxmList() {
  projectTableLoading.value = true; // 开启加载
  listTaskJcxm(queryTaskJcxmForm.value).then((res) => {
    taskJcxmList.value = res.rows;
    taskJcxmTotal.value = res.total;
    projectTableLoading.value = false; // 关闭加载
  });
}

// 点位列表删除按钮
const pointDeleteBtnClick = async (row) => {
  proxy.$modal
    .confirm(
      "删除该点位会将该点位下的点位信息及关联的检测项目信息全部删除，确定要删除吗？"
    )
    .then(async () => {
      await delPoint(row.pointId); // 根据点位id删除
      pointForm.value = {}; // 重置点位详情表单
      taskJcxmList.value = []; // 重置点位列表右侧检测方法列表
      proxy.$modal.msgSuccess("删除成功");
      const res2 = await listPoint1({ primaryId: customId.value }); // 删除后重新获取点位列表实现刷新
      pointList.value = res2.data;
    })
    .catch(() => { });
};

// 在线设备逻辑区域

const temp = ref(""); // 临时变量，用户保存设备id
// 设备新增弹出层保存按钮
const addOrEditSaveBtnClick = async () => {
  let validFlag = true;
  for (let i = 0; i < deviceForm.value.deviceJcxmTargetList.length; i++) {
    if (
      !(
        deviceForm.value.deviceJcxmTargetList[i].techName &&
        deviceForm.value.deviceJcxmTargetList[i].labName &&
        deviceForm.value.deviceJcxmTargetList[i].sampleName
      )
    ) {
      validFlag = false;
      break;
    }
  }

  if (!validFlag) {
    proxy.$modal.msgError("技术指标表格项均不能为空");
    return;
  }

  if (validFlag) {
    proxy.$refs["dialogRef"].validate(async (valid) => {
      if (!valid) return Promise.reject(false);

      await addOrEditMethodAPI(deviceForm.value); // 新增检测项目
      const { data: res } = await getDevice(deviceForm.value.deviceId); // 根据右侧新增项目检测列表中的设备id，获取对应设备详情信息
      addDeviceInfo.value = res; // 保存设备详情信息

      addDeviceInfo.value.deviceId = deviceForm.value.deviceId; // 保存设备id

      if (deviceForm.value.dJId) {
        proxy.$modal.msgSuccess("编辑成功");
      } else {
        proxy.$modal.msgSuccess("新增成功");
      }
      isShowAddDialog.value = false; // 关闭Dialog
      deviceForm.value.deviceJcxmTargetList = []; // 重置弹出框下方表格数据
      proxy.$refs["dialogRef"].resetFields(); // 重置dialog中的表单
      // resolve(); // 多余
    });
  }
};

// 新增/编辑检查项目Dialog => 取消按钮
const addOrEditCancelBtnClick = () => {
  isShowAddDialog.value = false; // 关闭dialog
  proxy.$refs["dialogRef"].resetFields(); // 重置表单
};

// 新增设备基础信息按钮
const deviceBasicInfoAddBtnClick = async () => {
  addDeviceInfo.value = {}; // 重置右侧表单
  proxy.$refs["addDeviceInfoRef"].resetFields(); // 重置右侧表单校验
};

// 新增设备基础信息 => 保存按钮
const addDeviceInfoSaveBtnClick = (isAuto) => {
  return new Promise((resolve) => {
    proxy.$refs["addDeviceInfoRef"].validate(async (valid) => {
      if (!valid) return Promise.reject(false);

      addDeviceInfo.value.customId = form.value.customId; // 保存客户id

      const { data: deviceId } = await addBasicDeviceInfoAPI(
        addDeviceInfo.value
      ); // 根据新增设备基础信息，获取新增后的设备id

      const { data: res } = await listDevice({ customId: form.value.customId }); // 获取设备列表，实现刷新
      deviceList.value = res;
      if (!isAuto) {
        if (addDeviceInfo.value.deviceId) {
          proxy.$modal.msgSuccess("编辑成功");
        } else {
          addDeviceInfo.value.deviceId = deviceId;
          proxy.$modal.msgSuccess("新增成功");
        }
      }

      resolve();
    });
  });
};

// 在线设备列表 => 点击切换
const deviceListRowClick = async (row) => {
  proxy.$refs["addDeviceInfoRef"].resetFields(); // 重置右侧设备详情表单
  const { data: res } = await getDevice(row.deviceId); // 根据当前行的设备id获取设备详情
  temp.value = row.deviceId; // 将当前设备id存储到全局
  addDeviceInfo.value = res; // 保存当前设备详情
};

// 新增/编辑检查项目 => 技术指标 => 点击新增递增1行
const addNewRowBtnClick = async () => {
  // 如果当前这个数组长度为0,增加一行
  if (deviceForm.value.deviceJcxmTargetList.length < 1) {
    getSeqId().then((res) => {
      deviceForm.value.deviceJcxmTargetList.push({ targetId: res.data }); // 新增一行
    });
  } else {
    // 如果当前数组长度大于0,校验上一行的表单是否通过校验,如通过继续新增,如没通过不新增
    proxy.$refs["dialogRef"].validate(async (valid) => {
      if (!valid) return false;
      getSeqId().then((res) => {
        // deviceForm.value.deviceJcxmTargetList.push({ targetId: res.data })
        deviceForm.value.deviceJcxmTargetList.push({ targetId: res.data });
      });
    });
  }
};

// 监听检测项目id的改变获取对应的参比方法号
const jcxmSelectChange = async (jcxmId) => {
  delete deviceForm.value.mJId;
  methodList.value = [];
  const res = await getArgumentsMethodIdAPI({
    jcxmId: jcxmId,
    jclbId: addDeviceInfo.value.jclbId,
  });
  methodList.value = res.data;
};

// 在线设备列表 => 点击删除
const deleteDeviceListItemBtnClick = async (row) => {
  proxy.$modal
    .confirm("是否确认该条删除数据项？")
    .then(async () => {
      await delDevice(row.deviceId);
    })
    .then(async () => {
      proxy.$modal.msgSuccess("删除成功");
      const res2 = await listDevice({ customId: customId.value });
      deviceList.value = res2.data;
      addDeviceInfo.value = {
        deviceJcxmList: [],
      };
      proxy.$refs["addDeviceInfoRef"].resetFields();
    });
};

// 在线设备列表 => 检测项目列表 => 点击编辑
const editDeviceInfo = async (row) => {
  isShowAddDialog.value = true; // 开启dialog
  const res = await echoAPI(row.dJId); // 根据djid查询当前检测项目信息
  const res2 = await getJcxmList(addDeviceInfo.value.jclbId); // 获取检测项目列表
  jcxmList.value = res2.data;
  if (res.data.jcxmId) jcxmSelectChange(res.data.jcxmId);
  deviceForm.value = res.data;
};

// 关闭新增/编辑检查项目钩子
const closedDialog = () => {
  deviceForm.value = {
    deviceJcxmTargetList: [],
  };
};

// 在线设备列表 => 右检测项目列表 => 点击删除
const deleteMethodItem = async (row) => {
  proxy.$modal
    .confirm("是否确认删除该条数据项？")
    .then(async () => {
      await deleteJcxmAPI(row.dJId.split(","));
      const { data: res } = await getDevice(temp.value); // 删除后刷新对应设备列表下的检测方法列表
      addDeviceInfo.value = res;
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
};

// 新增/编辑检查项目 => 技术指标 => 点击删除
const deleteDialogNewRows = (index) => {
  deviceForm.value.deviceJcxmTargetList.splice(index, 1);
};

// 在线设备详情校验规则
const deviceInfoRules = ref({
  location: [{ required: true, message: "安装位置不能为空", trigger: "blur" }],
  jclbId: [{ required: true, message: "请选择检测类别", trigger: "change" }],
  orderId: [{ required: true, message: "排序号不能为空", trigger: "blur" }],
  jd: [
    {
      pattern:
        /^(((\d|[1-9]\d|1[1-7]\d|0)\.\d{0,6})|(\d|[1-9]\d|1[1-7]\d|0{1,3})|180\.0{0,6}|180)$/,
      message: "输入错误",
      trigger: "blur",
    },
  ],
  wd: [
    {
      pattern: /^([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/,
      message: "输入错误",
      trigger: "blur",
    },
  ],
});

function transformation(row) {
  if (row) {
    const a = proxy.getSupAndSub(row);
    return a;
  }
}

const jwdForm = ref({});
function editJdClick(name) {
  proxy.$refs[name + "Ref"].validateField("jd", (isOpen) => {
    if (isOpen) {
      jdDialog.value = true;
      if (name == "custom" ? form.value.jd : addDeviceInfo.value.jd) {
        let tempJd = name == "custom" ? form.value.jd : addDeviceInfo.value.jd;
        getDms({ jd: tempJd }).then((res) => {
          jwdForm.value = res.data;
          jwdForm.value.isName = name;
        });
      } else {
        jwdForm.value = {};
        jwdForm.value.isName = name;
      }
    }
  });
}
function editWdClick(name) {
  proxy.$refs[name + "Ref"].validateField("wd", (isOpen) => {
    if (isOpen) {
      wdDialog.value = true;
      if (name == "custom" ? form.value.wd : addDeviceInfo.value.wd) {
        let temp = name == "custom" ? form.value.wd : addDeviceInfo.value.wd;
        getDms({ wd: temp }).then((res) => {
          jwdForm.value = res.data;
          jwdForm.value.isName = name;
        });
      } else {
        jwdForm.value = {};
        jwdForm.value.isName = name;
      }
    }
  });
}

function jdSave() {
  if (
    !jwdForm.value.degrees &&
    !jwdForm.value.minutes &&
    !jwdForm.value.seconds
  ) {
    proxy.$modal.msgError("请填写完整的经度");
  } else {
    getLatiAndLong(jwdForm.value).then((res) => {
      if (jwdForm.value.isName == "addDeviceInfo") {
        addDeviceInfo.value.jd = res.data;
      } else {
        form.value.jd = res.data;
      }
      jdDialog.value = false;
    });
  }
}

function wdSave() {
  if (
    !jwdForm.value.degrees &&
    !jwdForm.value.minutes &&
    !jwdForm.value.seconds
  ) {
    proxy.$modal.msgError("请填写完整的纬度");
  } else {
    getLatiAndLong(jwdForm.value).then((res) => {
      if (jwdForm.value.isName == "addDeviceInfo") {
        addDeviceInfo.value.wd = res.data;
      } else {
        form.value.wd = res.data;
      }
      wdDialog.value = false;
    });
  }
}
</script>

<style scoped>
sub,
sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
}

sup {
  top: -0.5em;
}

sub {
  bottom: -0.25em;
}
</style>
